<?php

namespace utils;


use CURLFile;
use OSS\OssClient;


/**
 * 阿里云 obs文件上传
 * Class OSS
 * @package utils
 */
class AliOSS
{
    protected $client;
    protected $config = [];

    protected static $KeyId = 'LTAI4GGPQ76TPwWYTqDHEjS5';
    protected static $KeySecret = '7oJx9bF86WWDjSTYriQWC6HDFHy3mz';
    protected static $Endpoint = 'oss-cn-beijing.aliyuncs.com';
    protected static $bucket = 'esaas-club';

    public static function new_oss()
    {
        //实例化OSS
        return new OssClient(static::$KeyId, static::$KeySecret, static::$Endpoint);
    }

    public static function uploadFile($file, $type = 0)
    {
        try {
            $file_info=$file->getInfo();
            $filename = $file_info['name'];
            $tmp_name=$file_info['tmp_name'];
            //文件目录
            $file_dir = 'img';
            if (!empty($file_info['dir'])) {
                $file_dir = $file_info['dir'];
            }
            //获取扩展名
            $extension_name = call_user_func(static function () use ($filename) {
                $str = strrev($filename);
                return strrev(strstr($str, '.', true));
            });
            //验证文件格式和文件大小
            if (!empty($file_info['ext'])) {
                if (!in_array($extension_name, ['png','jpg','jpeg'])) {
                    return apiError('40000','文件格式错误');
                }
            }
            if (!empty($file_info['size'])) {
                $file_size = $file_info['size'];
                if ($file_size > 2 * 1024 * 1024) {
                    return apiError('40000','文件大小超过最大限制30M');
                }
            }
            //实例化对象 将配置传入
            $ossClient = self::new_oss();

            //这里是有sha1加密 生成文件名 之后连接上后缀
            $ossFileName = sha1(date('YmdHis') . uniqid('', true)) . '.' . $extension_name;
            //执行阿里云上传
            $alifile = $file_dir . '/' . $ossFileName;//阿里云路径

            $result = $ossClient->uploadFile(self::$bucket, $alifile,$tmp_name);
            if ($type) {
                $res = [
                    'path' => $result['info']['url'],
                    'name' => $filename,
                    'oss_name' => $ossFileName,
                    'extension_name' => $extension_name,
                    'file_size' => $result['info']['size_upload'],
                    'file_dir' => $file_dir
                ];
            } else {
                $res = ['path'=>$result['info']['url']];
            }
            return $res;
        } catch (\Exception $e) {
            return apiError('图片存储失败');

        }
    }
}

